package com.yc.web.servlets;

import com.yc.bean.Userlist;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.*;

@WebServlet("/admin/user.action")
public class UserServlet extends BaseServlet{
    public void findAllUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException, ParseException {
      Userlist c=super.parseObjectFromRequest(req,Userlist.class);
       int page=1;
       if (req.getParameter("page")!=null){
           page=Integer.parseInt(req.getParameter("page"));
       }
       int limit=2;
       if (req.getParameter("limit")!=null){
           limit=Integer.parseInt(req.getParameter("limit"));
       }
       int skip=(page-1)*limit;
        //select*
        String sql="select * from user where 1=1 ";
        String sql2="select count(*) as total from user where 1=1 ";
        List<Object>params=new ArrayList<>();
        if (c.getUserid()!=null){
            sql+=" and userid=? ";
            sql2+=" and userid=? ";
            params.add(c.getUserid());
        }
        if (c.getUsername()!=null && !"".equals(c.getUsername())){
            sql+="and username like '%"+c.getUsername()+"%' ";
            sql2+="and username like '%"+c.getUsername()+"%' ";
           // params.add(c.getUsername());
        }
        if (c.getEmail()!=null && !"".equals(c.getEmail())){
            sql+="and email like '%"+c.getEmail()+"%' ";
            sql2+="and email like '%"+c.getEmail()+"%' ";
            //params.add(c.getEmail());
        }
        if (c.getStatus()!=null){
            sql+="and status ="+c.getStatus();
            sql2+="and status ="+c.getStatus();
            //params.add(c.getEmail());
        }
        List<Userlist>list=db.select(Userlist.class,sql+"   order by userid limit "+limit+" offset "+skip,params.toArray());
        List<Map<String,Object>>result=db.select(sql2,params.toArray());
        int total=Integer.parseInt(result.get(0).get("total").toString());
        Map<String,Object>map=new HashMap<String,Object>();
        map.put("code",0);
        map.put("msg","查询用户成功");
        map.put("data",list);
        map.put("count",total);
        super.writeObiectJson(map,resp);

    }
    public void delUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException, ParseException {
        Userlist c=super.parseObjectFromRequest(req,Userlist.class);
        String sql="delete from user where userid=?";
        int r=db.doUpdate(sql,c.getUserid());

        Map<String,Object>map=new HashMap<String,Object>();
        if (r>0){
            map.put("code",0);
            map.put("msg","删除用户成功");
            resp.setStatus(200);
        }else {
            resp.setStatus(500,"删除用户失败");
            map.put("code",1);
            map.put("msg","删除用户失败");

        }
        super.writeObiectJson(map,resp);

    }
    public void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException, ParseException {
        Userlist c=super.parseObjectFromRequest(req,Userlist.class);
        String sql = "UPDATE user " +
                "SET username = ?, " +
                "    email = ?, " +
                "    address = ?, " +
                "    status = ? " +
                "WHERE userid = ?;";
        if(c.getStatus()==null){
            c.setStatus(1);
        }
        int r=db.doUpdate(sql,c.getUsername(),c.getEmail(),c.getAddress(),c.getStatus(),c.getUserid());

        Map<String,Object>map=new HashMap<String,Object>();
        if (r>0){
            map.put("code",0);
            map.put("msg","更新用户成功");
            resp.setStatus(200);
        }else {
            resp.setStatus(500,"更新用户失败");
            map.put("code",1);
            map.put("msg","更新用户失败");

        }
        super.writeObiectJson(map,resp);

   }
    public void allUsing(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        String userid = req.getParameter("userid"); // 假设收到的是字符串 "1,2"
        String[] userIds = userid.split(","); // 拆分字符串，得到用户ID数组 ["1", "2"]

// 构建更新数据库的 SQL 语句
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("UPDATE user SET status = 0 WHERE userid IN (");

// 生成 SQL 中的占位符
        for (int i = 0; i < userIds.length; i++) {
            sqlBuilder.append("?");
            if (i < userIds.length - 1) {
                sqlBuilder.append(", ");
            }
        }
        sqlBuilder.append(");");

        String sql = sqlBuilder.toString();

// 假设 db.doUpdate 方法可以执行更新操作，参数为 SQL 语句和用户ID数组
        int r = db.doUpdate(sql, (Object[]) userIds);
        Map<String,Object>map=new HashMap<String,Object>();
        System.out.println("SQL: " + sql);
        System.out.println("User IDs: " + Arrays.toString(userIds));
        if (r>0){
            map.put("code",0);
            map.put("msg","启用用户成功");
            resp.setStatus(200);
        }else {
            resp.setStatus(500,"启用用户失败");
            map.put("code",1);
            map.put("msg","启用用户失败");

        }
        super.writeObiectJson(map,resp);}
    public void allStop(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        String userid = req.getParameter("userid"); // 假设收到的是字符串 "1,2"
        String[] userIds = userid.split(","); // 拆分字符串，得到用户ID数组 ["1", "2"]

// 构建更新数据库的 SQL 语句
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("UPDATE user SET status = 1 WHERE userid IN (");

// 生成 SQL 中的占位符
        for (int i = 0; i < userIds.length; i++) {
            sqlBuilder.append("?");
            if (i < userIds.length - 1) {
                sqlBuilder.append(", ");
            }
        }
        sqlBuilder.append(");");

        String sql = sqlBuilder.toString();

// 假设 db.doUpdate 方法可以执行更新操作，参数为 SQL 语句和用户ID数组
        int r = db.doUpdate(sql, (Object[]) userIds);
        Map<String,Object>map=new HashMap<String,Object>();
        System.out.println("SQL: " + sql);
        System.out.println("User IDs: " + Arrays.toString(userIds));
        if (r>0){
            map.put("code",0);
            map.put("msg","停用用户成功");
            resp.setStatus(200);
        }else {
            resp.setStatus(500,"停用用户失败");
            map.put("code",1);
            map.put("msg","停用用户失败");

        }
        super.writeObiectJson(map,resp);}

}
